<?php


namespace app\api\model;

use Guzzle\Http\Client;
use think\Cache;
use think\Model;

class WxMessage extends Model
{

    /**
     * 微信公众号消息通知几个场景
     *
     *  1. appointmentSuccess     服务进度提醒 （1.用户线上预约后，推送消息给客户）
     * param( :title  :name  :status  :time  :remark)
     * 2. s_startService         推送消息给服务人员   订单受理通知
     * param( :title  :server_name  :time  :username  :user_phone :user_address :remark)
     * 3. appointmentService    师傅接单，点击开始服务，客户推送通知
     * param( :server_user_name  :server_user_mobile  :time)
     * 4. changeServerTime    服务进度提醒    (2.修改订单时间,推送消息给客户)
     * param( :title  :name  :status  :time  :remark)
     * 5. startServer  服务进度提醒    (3.师傅上门开始服务，推送消息给客户)
     * param( :title  :name  :status  :time  :remark)
     * 6. overService    推送消息给客户（订单完成 ）
     * param( :name  :time  :remark)
     * 7. s_overServer   服务进度提醒    （4.服务结束，发送通知给服务人员）
     * param( :title  :name  :status  :time  :remark)
     */

    public static function sendMessage($type, $params = [])
    {

        if ($type == 1) {
            return self::appointmentSuccess($params);
        }
        if ($type == 2) {
            return self::s_startService($params);
        }
        if ($type == 3) {
            return self::appointmentService($params);
        }
        if ($type == 4) {
            return self::changeServerTime($params);
        }
        if ($type == 5) {
            self::startServer($params);
        }
        if ($type == 6) {
            self::overService($params);
        }
        if ($type == 7) {
            return self::s_overServer($params);
        }
        if ($type == 8) {
            return self::apply_success($params);
        }
        if ($type == 9) {
            return self::apply_error($params);
        }
        if ($type == 10) {
            return self::fenpeiSuccess($params);
        }
        if ($type == 11) {
            //预售通知
            return self::order_change($params);
        }
        if ($type == 12) {
            //线下订单短信通知
            return self::send_sms_message($params);
        }

        if ($type == 13) {
            //YPP 后台线下订单短信通知
            return self::send_sms_message1($params);
        }

    }

    public static function send_sms_message($param)
    {
        $username = config("wechat.sms_name");
        $password = config("wechat.sms_password");
        $username = !empty($username) ? $username : 'yelin';
        $password = !empty($password) ? md5($password) : md5('831206');

        $template1 = 'http://api.smsbao.com/sms?u='.$username.'&p='.$password.'&m='.$param['mobile'].'&c=【快洗到家】'.$param['client_name'].'您好，师傅'.$param['server_user_name'].'：为您提供'.$param['server_name'].'服务，请给师傅一个评价吧！非常满意回复 5，满意回复 4，一般回复 3，不满意回复 2，非常不满意回复 1。回复免费的哟。';

        $client = new Client($template1);
//        $req = $client->get($url);
        $client = $client->get();

        $json = $client->send();

        $json = $json->getBody();

        $return = json_decode($json, true);

        var_dump($return);
    }

    //YPP 后台线下订单短信通知
    public static function send_sms_message1($param)
    {
        $username = config("wechat.sms_name");
        $password = config("wechat.sms_password");
        $username = !empty($username) ? $username : 'yelin';
        $password = !empty($password) ? md5($password) : md5('831206');

        //【快洗到家】{ClientName}您好，维保师傅：{WorkerName}，电话：{phonenumber}，将为您提供{ServerName}服务。为保证您的权益不建议现金交易，服务过程中有任何疑问请拨打：4000760882。
        $template1 = 'http://api.smsbao.com/sms?u='.$username.'&p='.$password.'&m='.$param['mobile'].'&c=【快洗到家】'.$param['client_name'].'您好，维保师傅：'.$param['server_user_name'].'，电话：'.$param['server_phone'].'，将为您提供'.$param['server_name'].'服务。为保证您的权益不建议现金交易，服务过程中有任何疑问请拨打：4000760882。';

        $client = new Client($template1);
//        $req = $client->get($url);
        $client = $client->get();

        $json = $client->send();

        $json = $json->getBody();

        $return = json_decode($json, true);
        
        return $return;
    }
    //预约商品可以购买通知
    public static function order_change($params)
    {
        $data = [
            'title'=>'预售商品使用通知',
            'openid' => $params['openid'],
            'name' => $params['name'],
            'mobile' => $params['mobile'],
            'order_str' => $params['order_str'],
            'order_status' => $params['order_status'],
            'sum_money' => $params['sum_money'],
            'remark' => '您下的预售商品马上就可以使用了',
        ];
        return self::send($data, 6);
    }

    //师傅接单，点击开始服务，客户推送通知
    public static function appointmentService($params)
    {
        $data = [
            'openid' => $params['openid'],
            'nickname' => $params['name'],
            'mobile' => $params['mobile'],
            'type' => $params['type'],
            'createtime' => $params['time'],
        ];
        return self::send($data, 1);
    }

    //推送消息给客户（订单完成 ）
    public static function overService($param)
    {
        $data = [
            'openid' => $param['openid'],
            'name' => $param['name'],
            'createtime' => date('Y-m-d H:i:s', time()),
            'remark' => '感谢您选择快洗到家服务，也欢迎您对本次服务进行监督和评价，如有问题请联系客服：400-0760-882',
        ];
        $url = 'pages/yuyue/order';
        return self::send($data, 2,$url);
    }

    //推送消息给服务人员   订单受理通知
    public static function s_startService($param)
    {
        $data = [
            'first_data' => '预约服务下单提醒',
            'openid' => $param['openid'],
            'name' => $param['type_name'],
            'time' => $param['time'],
            'username' => $param['username'],
            'user_phone' => $param['user_phone'],
            'user_address' => $param['user_address'],
            'remark' => '请及时做好准备，准时上门服务',
        ];
        $url = 'pages/server/index';
        return self::send($data, 3,$url);
    }

    //服务进度提醒 （1.用户线上预约后，推送消息给客户）
    public static function appointmentSuccess($param)
    {
        $data = [
            'openid' => $param['openid'],
            'first' => '服务下单成功',
            'name' => $param['name'],
            'status' => '下单成功，等待分配上门服务人员',
            'createtime' => $param['time'],
            'remark' => '请耐心等待平台人员分配',
        ];
        return self::send($data, 4);
    }

    public static function fenpeiSuccess($param)
    {
        $data = [
            'openid' => $param['openid'],
            'first' => '人员分配成功',
            'name' => $param['name'],
            'status' => '分配人员成功，等待分配上门服务人员',
            'createtime' => $param['time'],
            'remark' => '请耐心等待服务人员上门',
        ];
        return self::send($data, 4);

        $sms_str = '分配人员成功，等待分配上门服务人员。人员：'.$param['name'].'。';


    }

    //服务进度提醒    (2.修改订单时间,推送消息给客户)
    public static function changeServerTime($param)
    {
        $data = [
            'openid' => $param['openid'],
            'first' => '服务完成通知',
            'name' => $param['type'],
            'status' => '等待确认完成',
            'createtime' => date('Y-m-d H:i:s',time()),
            'remark' => '请点击进入小程序进行确认服务',
        ];
        $url = 'pages/bill/bill?order_id='.$param['order_id'];
        self::send($data, 4 ,$url);
    }

    //服务进度提醒    （3.师傅上门开始服务，推送消息给客户）
    public static function startServer($param)
    {
        $data = [
            'openid' => $param['openid'],
            'first' => '开始服务通知',
            'name' => $param['name'],
            'status' => '已开始服务',
            'createtime' => date('Y-m-d H:i:s', time()),
            'remark' => '服务人员已开始为您服务，欢迎监督服务。',
        ];
        return self::send($data, 4);
    }

    //服务进度提醒    （4.服务结束，发送通知给服务人员）
    public static function s_overServer($param)
    {
        $data = [
            'openid' => $param['openid'],
            'first' => '服务完成通知',
            'name' => $param['name'],
            'status' => '确认完成服务',
            'createtime' => date('Y-m-d H:i:s', time()),
            'remark' => '本次服务已结束',
        ];
        $url = 'pages/server/index';
        return self::send($data, 4,$url);
    }

    //审核结果提醒 （通过）
    public static function apply_success($param)
    {
        $data = [
            'openid' => $param['openid'],
            'first' => '恭喜您，您的审核已通过',
            'type' => '服务人员审核',
            'status' => '审核通过',
            'createtime' => date('Y-m-d H:i:s', time()),
            'remark' => $param['remark']
        ];
        return self::send($data, 5);
    }

    //审核结果提醒 （通过）
    public static function apply_error($param)
    {
        $data = [
            'openid' => $param['openid'],
            'first' => '很抱歉，您的审核未通过',
            'type' => '服务人员审核',
            'status' => '审核拒绝',
            'createtime' => date('Y-m-d H:i:s', time()),
            'remark' => $param['remark']
        ];
        return self::send($data, 5);
    }

    public static function send($data, $type ,$url = null)
    {
        $access_token = self::getToken();
        if ($access_token) {
            $params = self::template($data, $access_token, $type, $url);
            $row = self::postMessageApi($params);
            log_print($row);
            return $row;
            //var_dump($row);
        }
    }

    public static function postMessageApi($params)
    {
        $url = 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/uniform_send?access_token=' . $params['access_token'];
        $response = posturl($url, $params);
//        $array = json_decode($response,true);
        if ($response['errmsg'] == 'ok') {
            return $response;
        } else {
            if($response['errcode'] == 40001){
                Cache::set(config("wechat.appid") . 'access_token', '');
            }
            log_print('模板消息发送失败222', $url, $response);
            return false;
        }
    }

    public static function getToken()
    {
        $access_token = Cache::get(config("wechat.appid") . 'access_token');
        if ($access_token) return $access_token;

        $appid = config("wechat.mini_appid");
        $secret = config("wechat.mini_secret");
//        $appid = config("wechat.appid");
//        $secret = config("wechat.secret");
        $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $appid . '&secret=' . $secret;
        $client = new Client($url);
//        $req = $client->get($url);
        $client = $client->get();

        $json = $client->send();

        $json = $json->getBody();

        $return = json_decode($json, true);

        if (!empty($return['access_token'])) {
            Cache::set(config("wechat.appid") . 'access_token', $return['access_token'], 7000); //缓存
            return $return['access_token'];
        } else {
            log_print('微信模板消息发送失败', $json, $appid, $secret, $url);
            return '';
        }
    }

    public static function template($data, $token, $type, $path = 'pages/index?foo=bar')
    {
        if (empty($data['openid'])) {
            log_print('openid不存在');
            log_print($data);
            //return false;
        }
        $template = self::getTemplate($type, $data);
        $params = [
            'access_token' => $token,
            'touser' => $data['openid'],
            'mp_template_msg' => [
                'appid' => config("wechat.appid"),
                'template_id' => $template['template_id'],
                'url' => config("wechat.return_url"),
                'miniprogram' => [
                    'appid' => config("wechat.mini_appid"),
                    'pagepath' => $path,
//                    'page' => $path,
                ],
                'data' => $template['template_data'],
            ],
        ];
        log_print($params);
        //print_r($params);die();
        return $params;
    }

    public static function getTemplate($type, $data)
    {
        $template_id = '';
        $template_data = '';
        if ($type == 1) {
            //开始服务
            $template_data = self::template1($data);
            $template_id = config("wechat.start_server");
        }
        if ($type == 2) {
            //结束服务
            $template_data = self::template2($data);
            $template_id = config("wechat.end_server");
        }
        if ($type == 3) {
            //服务端订单受理通知
            $template_data = self::template3($data);
            $template_id = config("wechat.process_notice");
        }
        if ($type == 4) {
            //服务进度提醒
            $template_data = self::template4($data);
            $template_id = config("wechat.progress_notice");
        }
        if ($type == 5) {
            //服务进度提醒
            $template_data = self::template5($data);
            $template_id = config("wechat.zizhi_apply");
        }
        if ($type == 6) {
            //预售商品提醒
            $template_data = self::template6($data);
            $template_id = config("wechat.order_change");
        }
        return [

            'template_id' => $template_id,
            'template_data' => $template_data,
        ];
    }

    //开始服务提醒
    public static function template1($data)
    {
        $data = [
            'first' => ['value' => '服务工单派工提醒', 'color' => '#173177'],
            'keyword1' => ['value' => $data['nickname'], 'color' => '#173177'],
            'keyword2' => ['value' => $data['mobile'], 'color' => '#173177'],
            'keyword3' => ['value' => $data['type'], 'color' => '#173177'],
            'keyword4' => ['value' => $data['createtime'], 'color' => '#173177'],
            'remark' => ['value' => '', 'color' => '#173177'],
        ];
        return $data;
    }

    //结束服务提醒
    public static function template2($data)
    {
        $data = [
            'first' => ['value' => '服务完成通知', 'color' => '#173177'],
            'keyword1' => ['value' => $data['name'], 'color' => '#173177'],
            'keyword2' => ['value' => $data['createtime'], 'color' => '#173177'],
            'remark' => ['value' => '', 'color' => '#173177'],
        ];
        return $data;
    }

    //订单受理通知
    public static function template3($data)
    {
        $data = [
            'first' => ['value' => $data['first_data'], 'color' => '#173177'],
            'keyword1' => ['value' => $data['name'], 'color' => '#173177'],
            'keyword2' => ['value' => $data['time'], 'color' => '#173177'],
            'keyword3' => ['value' => $data['username'], 'color' => '#173177'],
            'keyword4' => ['value' => $data['user_phone'], 'color' => '#173177'],
            'keyword5' => ['value' => $data['user_address'], 'color' => '#173177'],
            'remark' => ['value' => $data['remark'], 'color' => '#173177'],
        ];
        return $data;
    }

    //服务进度通知
    public static function template4($data)
    {
        $data = [
            'first' => ['value' => $data['first'], 'color' => '#173177'],
            'keyword1' => ['value' => $data['name'], 'color' => '#173177'],
            'keyword2' => ['value' => $data['status'], 'color' => '#173177'],
            'keyword3' => ['value' => $data['createtime'], 'color' => '#173177'],
            'remark' => ['value' => $data['remark'], 'color' => '#173177'],
        ];
        return $data;
    }

    //资质审核结果通知
    public static function template5($data)
    {
        $data = [
            'first' => ['value' => $data['first'], 'color' => '#173177'],
            'keyword1' => ['value' => $data['type'], 'color' => '#173177'],
            'keyword2' => ['value' => $data['createtime'], 'color' => '#173177'],
            'keyword3' => ['value' => $data['status'], 'color' => '#173177'],
            'keyword4' => ['value' => $data['remark'], 'color' => '#173177'],
            'remark' => ['value' => '', 'color' => '#173177'],
        ];
        return $data;
    }

    //资质审核结果通知
    public static function template6($data)
    {
        $data = [
            'first' => ['value' => $data['title'], 'color' => '#173177'],
            'keyword1' => ['value' => $data['name'], 'color' => '#173177'],
            'keyword2' => ['value' => $data['mobile'], 'color' => '#173177'],
            'keyword3' => ['value' => $data['order_str'], 'color' => '#173177'],
            'keyword4' => ['value' => $data['order_status'], 'color' => '#173177'],
            'keyword5' => ['value' => $data['sum_money'], 'color' => '#173177'],
            'remark' => ['value' => '', 'color' => '#173177'],
        ];
        return $data;
    }
}